//
//  YWFreedomPuzzleController.m
//  YWPhotoEditMaster
//
//  Created by jun peng on 2023/9/6.
//

#import "YWFreedomPuzzleController.h"
#import "YWPuzzleStatus.h"
#import "YWnsertPhotoView.h"

@interface YWFreedomPuzzleController ()

@property (weak, nonatomic) IBOutlet UIView *bgView;
@property(nonatomic,strong)NSMutableArray *puzzleArray;
@property (weak, nonatomic) YWnsertPhotoView *drawView;

@end

@implementation YWFreedomPuzzleController

-(NSMutableArray *)puzzleArray{
    if(_puzzleArray == nil){
        _puzzleArray = [NSMutableArray array];
    }
    return _puzzleArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];  NSLog(@"YWFreedomPuzzleController:%ld",self.photos.count);
    NSLog(@"YWFreedomPuzzleController:%ld",self.assets.count);
    
    NSMutableArray *mArray = [NSMutableArray array];
    for (UIImage *image in self.photos) {
        YWPuzzleStatus *status = [[YWPuzzleStatus alloc] init];
        status.image = image;
        [mArray addObject:status];
    }
    self.puzzleArray = mArray;
    
    
    //创建画view并添加到bgView
    YWnsertPhotoView *drawView = [[YWnsertPhotoView alloc] init];
    self.drawView = drawView;
    [self.bgView addSubview:drawView];
    
    MJWeakSelf
    [self.drawView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(weakSelf.bgView);
        
    }];
    
 
    
}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];

    for (YWPuzzleStatus *status in self.puzzleArray) {
        
        [self.drawView setPhotoImage:status.image];
    }
    
}


-(UIImage *)getCurrentLayer{
    
    //1.开启一个位图上下文
    UIGraphicsBeginImageContextWithOptions(self.bgView.size, NO, 0);
    
    //2.把画板上的内容渲染到上下文当中
    CGContextRef ctx =  UIGraphicsGetCurrentContext();
    [self.bgView.layer renderInContext:ctx];
    
    //3.从上下文当中取出一张图片
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    //4.关闭上下文
    UIGraphicsEndImageContext();
    
    return newImage;
}


@end
